package com.luoxiang.socialandroid.activity;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.ACCID;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.adapter.RvgiftAdapter;
import com.luoxiang.socialandroid.app.MyAppliaction;
import com.luoxiang.socialandroid.base.BaseActivity;
import com.luoxiang.socialandroid.bean.BeforeCallBean;
import com.luoxiang.socialandroid.bean.BlockBean;
import com.luoxiang.socialandroid.bean.GetMessageBean;
import com.luoxiang.socialandroid.bean.GetWhereBean;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.OurinfoBean;
import com.luoxiang.socialandroid.dialog.Bottomsheet6Dialog;
import com.luoxiang.socialandroid.dialog.TipDialog;
import com.luoxiang.socialandroid.fragment.GetImageFragment;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.CustomClickListener;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils;
import com.luoxiang.socialandroid.view.ExpandTextView2;
import com.luoxiang.socialandroid.view.ExpandTextView3;
import com.lxj.xpopup.XPopup;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.attachment.MsgAttachment;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.yunxin.kit.chatkit.ui.custom.GiftAttachment;
import com.netease.yunxin.kit.chatkit.ui.dialog.GiftDialog;
import com.netease.yunxin.kit.corekit.im.model.UserInfo;
import com.netease.yunxin.kit.corekit.im.utils.RouterConstant;
import com.netease.yunxin.kit.corekit.route.XKitRouter;
import com.netease.yunxin.nertc.ui.CallKitUI;
import com.netease.yunxin.nertc.ui.base.CallParam;

import java.util.List;
import java.util.UUID;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import retrofit2.http.GET;

public class GetimageActivity extends BaseActivity {
    private Button ic_back, img_sandian;
    private String icon, name, title, domain;
    private ImageView img_head;
    private TextView tv_name, tv_number, gohei, cancel, open_album;
    private ExpandTextView2 tv_titles;

    private int size;
    private Button btn_guanzhuorno, btn_sixin, btn_shipin;
    private int userId = -1, mposition;
    private String token;
    private int flag, block, dymainId, code;
    private Button btn_gift;
    private RecyclerView rv_gifts;
    private RvgiftAdapter adapter;
    private TextView now_coin;
    private Button btn_sendgift;
    private ViewPager2 viewPager;

    @Override
    protected void initListener() {
        ic_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        btn_guanzhuorno.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (flag == 0) {
                    flag = 1;
                    getfocus(EXTRA, token, userId, 1);
                    isguanzhu();
                } else {
                    flag = 0;
                    getfocus(EXTRA, token, userId, 0);
                    isguanzhu();
                }
            }
        });
        img_sandian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showBottomSheetDialog();
            }
        });
        btn_sixin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转到单聊界面
                if (userId != -1) {
                    XKitRouter.withKey(RouterConstant.PATH_CHAT_P2P_PAGE).withParam(RouterConstant.CHAT_KRY, new UserInfo(userId + "", "aaa", "")).withContext(GetimageActivity.this).navigate();
                }
            }
        });
        btn_gift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                GiftDialog giftDialog = new GiftDialog(GetimageActivity.this, userId + "", 2, dymainId + "");
                new XPopup.Builder(GetimageActivity.this)
                        .moveUpToKeyboard(true)
                        .asCustom(giftDialog)
                        .show();
                giftDialog.setOnSendSuccess(giftMessageBean -> {
                    MsgAttachment attachment = new GiftAttachment(giftMessageBean);
                    IMMessage customMessage =
                            MessageBuilder.createCustomMessage(String.valueOf(userId), SessionTypeEnum.P2P, getString(R.string.mi_liwuxiaoxi), attachment);
                    NIMClient.getService(MsgService.class).sendMessage(customMessage, false);
                    return null;
                });
            }
        });
        btn_shipin.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                MmkvUtil.INSTANCE.encode("userId", userId);
                getimPre(EXTRA, userId + "", token);
            }

            @Override
            protected void onFastClick() {

            }
        });
    }


    @Override
    protected void initLayout(Bundle savedInstanceState) {
        setContentView(R.layout.activity_getimage);
        setStatusBarTranslucent();
    }

    @Override
    protected void initView() {
        showLoading();
        token = MmkvUtil.INSTANCE.decodeString(TOKEN);
        ic_back = findViewById(R.id.ic_back);
        tv_name = findViewById(R.id.tv_name);
        tv_titles = findViewById(R.id.tv_titles);
        tv_number = findViewById(R.id.tv_number);
        btn_guanzhuorno = findViewById(R.id.btn_guanzhuorno);
        img_sandian = findViewById(R.id.img_sandian);
        btn_sixin = findViewById(R.id.btn_sixin);
        btn_gift = findViewById(R.id.btn_gift);
        btn_shipin = findViewById(R.id.btn_shipin);
        viewPager = findViewById(R.id.viewPager);
        tv_titles.setTextColor(Color.parseColor("#FFFFFF"));
        Intent intent = getIntent();
        icon = intent.getStringExtra("icon");
        name = intent.getStringExtra("name");
        title = intent.getStringExtra("title");
        domain = intent.getStringExtra("domain");
        userId = intent.getIntExtra("userId", 0);
        mposition = intent.getIntExtra("mposition", 1);

        dymainId = intent.getIntExtra("dymainId", 0);
        List<String> bannerList = (List<String>) intent.getSerializableExtra("bannerList");
        viewPager.setAdapter(new FragmentStateAdapter(getSupportFragmentManager(), getLifecycle()) {
            @Override
            public int getItemCount() {
                return bannerList.size();
            }

            @NonNull
            @Override
            public Fragment createFragment(int position) {
                GetImageFragment getImageFragment = new GetImageFragment();
                Bundle bundle = new Bundle();
                bundle.putString("getImage", bannerList.get(position));
                getImageFragment.setArguments(bundle);
                return getImageFragment;
            }
        });
        size = bannerList.size();
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                tv_number.setText(position + 1 + "/" + size);

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                super.onPageScrollStateChanged(state);
            }
        });

        if (bannerList != null) {
            img_head = findViewById(R.id.ic_header);
            Glide.with(MyAppliaction.getContext())
                    .load("https://dahuixiong.oss-cn-shenzhen.aliyuncs.com/" + icon)
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))//设置圆形头像
                    .into(img_head);
            img_head.setOnClickListener(view -> {
                Intent intent1 = new Intent(GetimageActivity.this, DetailsActivity.class);
                intent1.putExtra("userid", userId);
                startActivity(intent1);
            });
            tv_name.setText(name);
            tv_titles.setText(title);


        }

        //调用是否关注
        getwhetherFocus(EXTRA, userId, token);
        //调用是否拉黑
        getBlock(EXTRA, token, userId);
    }

    private void getimPre(String extra, String toUserId, String token) {
        NetUtils.getInstance().getApiService().getimPre(extra, toUserId, token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        com.blankj.utilcode.util.LogUtils.i("decryptStr10", decryptStr);
                        Gson gson = new Gson();
                        OurinfoBean bean = gson.fromJson(decryptStr, OurinfoBean.class);
                        TestActivity.ourinfoBean = bean;
                        if (bean.getCode() == 0) {
                            //可以发起通话
                            int accId = MmkvUtil.INSTANCE.decodeInt(ACCID);
                            String id = UUID.randomUUID().toString().replace("-", "");
                            CallParam param = CallParam.createSingleCallParam(2, accId + "", userId + "", null, null, id);
                            CallKitUI.startSingleCall(GetimageActivity.this, param);
                        } else {
                            ToastUtils.showShort(bean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }


    private void isguanzhu() {
        //是否关注
        if (flag == 0) {
            //未关注
            btn_guanzhuorno.setBackgroundResource(R.drawable.shepe_btnguanzhu);
            btn_guanzhuorno.setText(R.string.mi_guanzhu);
            btn_guanzhuorno.setTextColor(Color.parseColor("#FFFFFF"));
        } else {
            //已关注
            btn_guanzhuorno.setBackgroundResource(R.drawable.shape_noguanzhu);
            btn_guanzhuorno.setText(R.string.mi_yiguanzhu);
            btn_guanzhuorno.setTextColor(Color.parseColor("#999999"));

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        tv_number.setText("1" + "/" + size);
        getwhetherFocus(EXTRA, userId, token);
    }

    //关注的方法
    private void getfocus(String extra, String token, int toUserId, int type) {
        NetUtils.getInstance().getApiService().getfocus(extra, token, toUserId, type)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        com.blankj.utilcode.util.LogUtils.i("decryptStr10", decryptStr);
                        Gson gson = new Gson();
                        GetMessageBean getWhereBean = gson.fromJson(decryptStr, GetMessageBean.class);
                        if (getWhereBean.getCode() != 0) {
                            ToastUtils.showShort(getWhereBean.getMsg());
                            getwhetherFocus(EXTRA, userId, token);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getwhetherFocus(String extra, int userId, String token) {
        NetUtils.getInstance().getApiService().getwhetherFocus(extra, userId, token)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        clearLoading();
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        com.blankj.utilcode.util.LogUtils.i("decryptStr9", decryptStr);
                        Gson gson = new Gson();
                        GetWhereBean getWhereBean = gson.fromJson(decryptStr, GetWhereBean.class);
                        if (getWhereBean != null) {
                            if (getWhereBean.getData() != null) {
                                flag = getWhereBean.getData().getFlag();
                                int show = getWhereBean.getData().isShow();
                                if (show != 1) {
                                    btn_guanzhuorno.setVisibility(View.GONE);
                                    btn_sixin.setVisibility(View.GONE);
                                    btn_gift.setVisibility(View.GONE);
                                    btn_shipin.setVisibility(View.GONE);
                                } else {
                                    btn_guanzhuorno.setVisibility(View.VISIBLE);
                                    btn_sixin.setVisibility(View.VISIBLE);
                                    btn_gift.setVisibility(View.VISIBLE);
                                    btn_shipin.setVisibility(View.VISIBLE);

                                }
                            }
                        }
                        isguanzhu();
                    }

                    @Override
                    public void onError(Throwable e) {
                        clearLoading();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 控制底部导航栏的方法
     */
    public void showBottomSheetDialog() {
        Bottomsheet6Dialog tipDialog6 = new Bottomsheet6Dialog(GetimageActivity.this);
        if (block == 0) {
            tipDialog6.setCancel(getString(R.string.mi_lahei));
        } else {
            tipDialog6.setCancel(getString(R.string.mi_quxiaolahei));

        }
        tipDialog6.setOnCancelClickListener(new Function0<Unit>() {
            @Override
            public Unit invoke() {
                if (block == 0) {
                    TipDialog tipDialog = new TipDialog(GetimageActivity.this);
                    tipDialog.setTitle(getString(R.string.mi_caozuotishi));
                    tipDialog.setCancel(getString(R.string.mi_quxiao));
                    tipDialog.setContent(getString(R.string.mi_lahei_dialog_content));
                    tipDialog.setConfirm(getString(R.string.mi_queding));
                    tipDialog.setOnCancelClickListener(new Function0<Unit>() {
                        @Override
                        public Unit invoke() {
                            tipDialog.dismiss();
                            return null;
                        }
                    });
                    tipDialog.setOnConfirmClickListener(new Function0<Unit>() {
                        @Override
                        public Unit invoke() {
                            if (block == 0) {
                                block = 1;
                                tipDialog6.setCancel(getString(R.string.mi_quxiaolahei));
                                getBlocktorf(EXTRA, token, userId, 1);
                            } else {
                                block = 0;
                                tipDialog6.setCancel(getString(R.string.mi_lahei));
                                getBlocktorf(EXTRA, token, userId, 0);
                            }
                            tipDialog.dismiss();
                            return null;


                        }
                    });
                    new XPopup.Builder(GetimageActivity.this)
                            .asCustom(tipDialog)
                            .show();
                } else {
                    if (block == 0) {
                        block = 1;
                        tipDialog6.setCancel(getString(R.string.mi_quxiaolahei));
                        getBlocktorf(EXTRA, token, userId, 1);
                    } else {
                        block = 0;
                        tipDialog6.setCancel(getString(R.string.mi_lahei));
                        getBlocktorf(EXTRA, token, userId, 0);
                    }
                }
                return null;
            }
        });
        tipDialog6.setOnjubaoClickListner(new Function0<Unit>() {
            @Override
            public Unit invoke() {
                Intent intent = new Intent(GetimageActivity.this, ReportActivity.class);
                intent.putExtra("userId", userId);
                intent.putExtra("dynamicId", dymainId);
                startActivity(intent);
                tipDialog6.dismiss();
                return null;
            }
        });
        tipDialog6.setQuxiaoClickListner(new Function0<Unit>() {
            @Override
            public Unit invoke() {
                tipDialog6.dismiss();
                return null;
            }
        });
        new XPopup.Builder(GetimageActivity.this)
                .asCustom(tipDialog6)
                .show();
    }

    /**
     * 获取拉黑状态
     *
     * @param extra
     * @param token
     * @param toUserId
     */
    private void getBlock(String extra, String token, int toUserId) {
        NetUtils.getInstance().getApiService().getBlock(extra, token, toUserId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr41", decryptStr);
                        Gson gson = new Gson();
                        BlockBean bean = gson.fromJson(decryptStr, BlockBean.class);
                        if (bean != null) {
                            if (bean.getData() != null) {
                                block = bean.getData().getBlock();
                                LogUtils.i("laheishifou",block);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    /**
     * 拉黑/取消拉黑
     */
    private void getBlocktorf(String extra, String token, int toUserId, int block) {
        NetUtils.getInstance().getApiService().getImblock(extra, token, toUserId, block)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr42", decryptStr);

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


}